package com.xez.data
{
	import com.xez.util.FsConst;
	
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;

	/**
	 * 
	 * Web_Dir_Img
	 * 
	 * @author Coco
	 */	
	public class WebRoot extends CacheData
	{
		
		[Bindable]
		public var dirs:ArrayCollection = new ArrayCollection();
		
		[Bindable]
		public var name:String;
		
		public var isvip:Boolean;
		
		private var loaded:Boolean = false;
		
		public function WebRoot()
		{
		}
		
		override public function get cachename():String
		{
			return name;
		}
		
		public function get label():String
		{
			return  name;
		}
		
		public function get tip():String
		{
			var s:String = '';
			/*if (isvip)
				s = '<Vip>';
			else
				s = '';*/
			
			if (isnew)
				s = '<新>';	
			
			return s;
		}
		
		public function load():void
		{
			if (loaded)
				return;
			
			loaded = true;
			
			if (hasCache())
				loadDirsFromCache();
			
			if (!dirs || dirs.length == 0)
				msg = '正在加载数据';
			
			loadDirsFromUrl();
		}
		
		public function refresh():void
		{
			msg = '正在刷新数据';
			loadDirsFromUrl();
		}
		
		private function loadDirsFromUrl():void
		{
			var hs:HTTPService = new HTTPService();
			hs.resultFormat = 'text';
			hs.addEventListener(ResultEvent.RESULT, getdir_resultHandler);
			hs.addEventListener(FaultEvent.FAULT, getdir_faultHandler);
			hs.url = FsConst.GET_DIR_URL + '?webname=' + name;
			hs.method = 'POST';
			hs.send();
		}
		
		private function loadDirsFromCache():void
		{
			trace('load from cache', name);
			dirs = new ArrayCollection();
			var dirObjs:ArrayCollection;
			var bytes:ByteArray = getCache();
			
			if (bytes)
				dirObjs  = bytes.readObject() as ArrayCollection;
			
			if (dirObjs)
			{
				var dir:DirRoot;
				for each (var dirObj:Object in dirObjs)
				{
					dir = new DirRoot();
					dir.webname = name;
					dir.name = dirObj.name;
					dir.isvip = dirObj.isvip;
					dirs.addItem(dir);
				}
			}
		}
		
		private function getdir_resultHandler(e:ResultEvent):void
		{
			trace('load result', name);
			msg = null;
			
			var dirxml:XML = new XML(e.result);
			trace(name, e.result);
			if (dirxml)
			{
				dirs = new ArrayCollection();
				var dir:DirRoot;
				for (var i:int = 0; i < dirxml.dir.length(); i++)
				{
					// 设置目录数据
					dir = new DirRoot();
					dir.webname = name;
					dir.name = dirxml.dir[i].name;
					dir.isvip = dirxml.dir[i].isvip == '0' ? false : true;
					dirs.addItem(dir);
				}
				
				// 缓存数据
				var bytes:ByteArray = new ByteArray();
				bytes.writeObject(dirs);
				saveCache(bytes);
			}
		}
		
		private function getdir_faultHandler(e:FaultEvent):void
		{
			trace('load fault', name);
			msg = null;
		}
		
	}
}